import 'package:flutter/material.dart';
import 'package:chewie/chewie.dart';
import 'package:pacsun/components/appbar.dart';
import 'package:video_player/video_player.dart';

class VideoPlayerPage extends StatefulWidget {
  final String videoUrl;
  final String? heroTag;

  const VideoPlayerPage({
    super.key,
    required this.videoUrl,
    this.heroTag,
  });

  @override
  State<VideoPlayerPage> createState() => _WechatStyleVideoPreviewState();
}

class _WechatStyleVideoPreviewState extends State<VideoPlayerPage> {
  late VideoPlayerController _videoPlayerController;
  ChewieController? _chewieController;
  bool _isInitialized = false;

  @override
  void initState() {
    super.initState();
    _initializePlayer();
  }

  Future<void> _initializePlayer() async {
    _videoPlayerController = VideoPlayerController.networkUrl(
      Uri.parse(widget.videoUrl),
    );
    await _videoPlayerController.initialize();

    _chewieController = ChewieController(
      videoPlayerController: _videoPlayerController,
      autoPlay: true,
      looping: false,
      aspectRatio: _videoPlayerController.value.aspectRatio,
      // 微信风格：白色进度条和按钮
      materialProgressColors: ChewieProgressColors(
        playedColor: Colors.white,
        handleColor: Colors.white,
        backgroundColor: Colors.grey[700]!,
        bufferedColor: Colors.grey[500]!,
      ),
      // 只保留常用倍速
      playbackSpeeds: [1.0, 1.5, 2.0],
      showControlsOnInitialize: false,
      allowFullScreen: false, // 微信预览不全屏
      allowMuting: true,
      allowPlaybackSpeedChanging: true,
    );

    setState(() {
      _isInitialized = true;
    });
  }

  @override
  void dispose() {
    _videoPlayerController.dispose();
    _chewieController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final double aspectRatio =
        _isInitialized ? _videoPlayerController.value.aspectRatio : 9 / 16;

    return Scaffold(
      backgroundColor: Colors.black,
      appBar: CommonTransparentAppBar(),
      body: GestureDetector(
        onTap: () => Navigator.of(context).pop(), // 微信风格：点击空白处返回
        child: Center(
          child: _isInitialized
              ? Container(
                  color: Colors.black,
                  alignment: Alignment.center,
                  child: AspectRatio(
                    aspectRatio: aspectRatio,
                    child: widget.heroTag != null
                        ? Hero(
                            tag: widget.heroTag!,
                            child: Chewie(controller: _chewieController!),
                          )
                        : Chewie(controller: _chewieController!),
                  ),
                )
              : const CircularProgressIndicator(
                  color: Colors.white, strokeWidth: 2),
        ),
      ),
    );
  }
}
